package cn.xc.org.controller;

import cn.xc.basic.util.AjaxResult;
import cn.xc.basic.util.PageList;
import cn.xc.org.domain.Department;
import cn.xc.org.domain.Employee;
import cn.xc.org.query.DepartmentQuery;
import cn.xc.org.query.EmployeeQuery;
import cn.xc.org.service.IDepartmentService;
import cn.xc.org.service.IEmployeeService;
import cn.xc.system.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Api(value = "员工api",description = "员工CRUD")
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService employeeService;

    @GetMapping
    @ApiOperation(value = "查询所有")
    public List<Employee> findAll(){
        return employeeService.findAll();
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "查询单个对象")
    public Employee findOne(@PathVariable("id") Long id){
        return  employeeService.findById(id);
    }

    @PostMapping
    @ApiOperation(value = "分页查询")
    public PageList<Employee> queryPage(@RequestBody  EmployeeQuery employeeQuery){
        return employeeService.queryPage(employeeQuery);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除")
    public AjaxResult del(@PathVariable("id") Long id){
        try{
            employeeService.del(id);
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }
    @PatchMapping
    @ApiOperation(value = "批量删除")
    public AjaxResult patchDel(@RequestBody List<Long> ids){
        try{
            employeeService.patchDel(ids);
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(false,"删除失败");
        }
    }

    @PutMapping
    @ApiOperation(value = "添加和修改")
    public AjaxResult addOrUpdate(@RequestBody Employee employee){
        try{
            List<Employee> list = employeeService.findAll();
            Set<Long> set = new HashSet<>();
            for (Employee employee1 : list) {
                set.add(employee1.getId());
            }
            if(set.contains(employee.getId())==false){
                employeeService.add(employee);
            }else{
                employeeService.update(employee);
            }
            return new AjaxResult();
        }catch (Exception e){
            e.printStackTrace();
            return new AjaxResult(false,"操作失败");
        }
    }


}
